package com.zsk.shop.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.TokenInfo;
import com.zsk.shop.mapper.TokenInfoMapper;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@DS("minishop")
public class TokenInfoService extends ServiceImpl<TokenInfoMapper, TokenInfo> {

    public void invalidByToken(String token) {
        LambdaUpdateWrapper<TokenInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(TokenInfo::getInvalid, true);
        updateWrapper.eq(TokenInfo::getToken, token);
        this.update(updateWrapper);
    }

    public List<TokenInfo> queryUnInvalidTokensByUserId(Long userId, Integer userType, Boolean isGop) {
        LambdaQueryWrapper<TokenInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TokenInfo::getUserId, userId);
        queryWrapper.and(x -> x.eq(TokenInfo::getInvalid, false).ge(TokenInfo::getInvalidDate, new Date()));
        if (ToolUtil.isNotEmpty(isGop)) {
            queryWrapper.eq(TokenInfo::getIsGop, isGop);
        }
        queryWrapper.orderByDesc(TokenInfo::getId);
        return list(queryWrapper);
    }

    public TokenInfo queryUnInvalidTokenByUserId(Long userId) {
        LambdaQueryWrapper<TokenInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TokenInfo::getUserId, userId);
        queryWrapper.and(x -> x.eq(TokenInfo::getInvalid, false).ge(TokenInfo::getInvalidDate, new Date()));
        queryWrapper.orderByDesc(TokenInfo::getId);
        queryWrapper.last("limit 1");
        return getOne(queryWrapper);
    }

    public void invalidTokens(List<TokenInfo> tokenInfos) {
        if (ToolUtil.isEmpty(tokenInfos)) {
            return;
        }
        for (TokenInfo tokenInfo : tokenInfos) {
            tokenInfo.setInvalid(true);
            tokenInfo.setUpdateTime(new Date());
        }
        this.updateBatchById(tokenInfos);
    }

}
